<template>
  <el-card class="page_card" shadow="never">
    <template #header>
      <div class="card-header">
        <div class="left">
          {{ props.params.title }}

        </div>
        <div class="right">
          <el-button style="margin-left: 20px" type="primary" @click="goBack">
            返回列表
          </el-button>
        </div>
      </div>
    </template>

    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm" status-icon>
      <el-form-item label="新闻图片" prop="imgUrl">
        <el-upload class="avatar-uploaders" :action="HTTP_URI.UPLOADFILE" :show-file-list="false" :headers="headers"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="ruleForm.imgUrl" :src="ruleForm.imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
        <el-input placeholder="请输入" v-model="ruleForm.imgUrl" v-show="false" />
      </el-form-item>
      <el-form-item label="新闻标题" prop="title">
        <el-input placeholder="请输入" v-model="ruleForm.title" />
      </el-form-item>
      <el-form-item label="来源名称" prop="source">
        <el-input placeholder="请输入" v-model="ruleForm.source" />
      </el-form-item>
      <el-form-item label="来源地址" prop="remark">
        <el-input placeholder="请输入" v-model="ruleForm.remark" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <Editor ref="editorRef" :value="ruleForm.content" @updateValue="getValue"></Editor>
      </el-form-item>
      <el-form-item label="是否置顶" prop="isTop">
        <el-select style="width: 100%" v-model="ruleForm.isTop" placeholder="请选择">
          <el-option label="是" :value="1"></el-option>
          <el-option label="否" :value="0"></el-option>
        </el-select>
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer" style="margin-left: 100px;">
        <el-button @click="handleCloses(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="submit(ruleFormRef)">
          确 认
        </el-button>
      </span>
    </template>
  </el-card>
</template>

<script lang="ts" setup>
import { h, ref, onMounted, watch } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { REQUEST } from '@/api/request'
import { Plus } from '@element-plus/icons-vue'
import HTTP_URI from '@/api/base_url'
import { getToken } from '@/plugins/cookie'
const props = defineProps({
  params: Object
})
const ruleFormRef = ref<FormInstance>()
const editorRef = ref()
const emits = defineEmits(['ok'])
const headers = ref({
  'Token': getToken()
})
const ruleForm = ref({
  id: '',
  source: '',
  remark: '',
  type: '1',
  isTop: 0,
  imgUrl: '',
  content: '',
  title: ''
})
const rules = ref({
  source: [{ required: true, message: '请输入来源', trigger: 'change' }],
  title: [{ required: true, message: '请输入新闻标题', trigger: 'change' }],
  isTop: [{ required: true, message: '请选择是否置顶', trigger: 'change' }],
  imgUrl: [{ required: true, message: '请上传图片', trigger: 'change' }],
  content: [{ required: false, message: '请输入新闻内容', trigger: 'change' }],
  remark: [{ required: true, message: '请输入来源地址', trigger: 'change' }]

})
const getValue = (res: any) => {
  console.log(res, 'getValue');
  // ruleForm.value.content = res
}

onMounted(() => {
  ruleForm.value = {
    id: '',
    isTop: 0,
    source: '',
    type: '1',
    remark: '',
    imgUrl: '',
    content: '',
    title: ''
  }
  editorRef.value.setValues(ruleForm.value.content)
  if (props.params.row) {
    ruleForm.value = props.params.row
    editorRef.value.setValues(ruleForm.value.content)
  }
})
watch(() => props.params.row, (val: any) => {
  console.log(val, 'watch');
  if (val) {
    ruleForm.value = val
    editorRef.value.setValues(ruleForm.value.content)
  } else if (val == null) {
    ruleForm.value = {
      id: '',
      isTop: 0,
      source: '',
      type: '1',
      remark: '',
      imgUrl: '',
      content: '',
      title: ''
    }
    setTimeout(() => editorRef.value.setValues(ruleForm.value.content), 200)
  }
}, { deep: true })
const handleAvatarSuccess = (response: any) => {
  ruleForm.value.imgUrl = response.data.url
}

const beforeAvatarUpload = (rawFile: any) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('上传图片格式仅支持jpg、png')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片大小不能超过 10MB')
    return false
  }
  return true
}
const handleCloses = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  goBack()
}
const goBack = () => {
  ruleForm.value = {
    id: '',
    isTop: 0,
    source: '',
    type: '1',
    remark: '',
    imgUrl: '',
    content: '',
    title: ''
  }
  editorRef.value.setValues(ruleForm.value.content)
  emits('go', { view: 'ActiveList', params: { row: 'ok' } })
}
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {

      if (props.params.title === '新增行业新闻') {
        ruleForm.value.content = editorRef.value.data.content
        REQUEST.POST('NEWSADD', ruleForm.value).then((res: any) => {
          if (res.status === 200) {
            ElMessage({
              type: 'success',
              message: '添加成功！'
            })
            formEl.resetFields()
            goBack()
          } else {
            ElMessage({
              type: 'warning',
              message: res.message
            })
          }
        })
      } else {
        ruleForm.value.content = editorRef.value.data.content
        REQUEST.POST('NEWSEDIT', ruleForm.value).then((res: any) => {
          if (res.status === 200) {
            ElMessage({
              type: 'success',
              message: '编辑成功！'
            })
            formEl.resetFields()
            goBack()
          } else {
            ElMessage({
              type: 'warning',
              message: res.message
            })
          }
        })

      }
    }
  })
}
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.demo-ruleForm {
  max-width: 900px;
}

.avatar-uploaders {
  width: 120px;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px #dcdfe6 dashed;
  cursor: pointer;
  border-radius: 5px;
}

.avatar-uploaders:hover {
  border: 1px #409eff dashed;
}

.avatar-uploader-icon {
  font-size: 32px;
  color: #cccccc;
}

.avatar-uploaders .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
